/**
 * Module dependencies.
 */

var join = require('path').join,
	fs = require('fs');
	express = require('express'),
	ndir = require('ndir'),
	i18n = require('i18n'),
	//Mongolian = require('./lib/mongolian'),
	//
	config = require('./web.config'),
	routes = require('./routes'),
	logger = require('./lib/log');

//var mongoserver = new Mongolian;// Create a server instance with default host and port
//mongoserver.log = logger;
//var db = mongoserver.db(config.db.dbname);  // Get database

module.exports = app = express();

// Configuration
i18n.configure({
  // setup some locales - other locales default to en silently
  locales: ['en', 'zh'],
  // where to register __() and __n() to, might be "global" if you
  // know what you are doing
  register: global
});

// ensure upload dir exists
ndir.mkdir(config.site.upload_dir, function(err) {
  if (err) {
    throw err;
  }
});

// configuration in all env
app.configure(function() {
  app.set('views', config.app.view.dir);
  app.engine(config.app.view.engine, config.app.view.register_func);
  app.set('view engine', config.app.view.engine);
  //app.set('view options',{layout:false});
  //app.register(config.app.view.register_suffix, config.app.view.register_func);
  app.use(express.bodyParser({uploadDir: config.app.views_dir}));
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({
    secret: config.site.session_secret
  }));
  app.use(function (req, res, next) {
    var lang = req.session.lang;
    if(lang){
      i18n.setLocale(req, lang);
      next();
    }else
      i18n.init(req, res, next);
  });

  // custom middleware
  //app.use(require('./controllers/sign').auth_user);

  var csrf = express.csrf();
  app.use(function(req, res, next) {
    // ignore upload image
    if (req.body && req.body.user_action === 'upload_image') {
      return next();
    }
    csrf(req, res, next);
  });
});


if (process.env.NODE_ENV !== 'test') {
  // plugins
  var plugins = config.plugins || [];
  for (var i = 0, l = plugins.length; i < l; i++) {
    var p = plugins[i];
    //app.use(require('./plugins/' + p.name)(p.options));
  }
}

// set static, dynamic helpers
app.locals({
  config: config
});

app.locals({
  csrf: function(req, res) {
    return req.session ? req.session._csrf : '';
  }
});

/*app.use(function(err, req, res, next){
  if( err == 403 ) {
    res.render('403');
  } else if( err == 404 ) {
    res.render('404');
  } else if( err == 500 ) {
    res.render('500');
  } else {
    res.render('error', {errorCode : err});
    // next(err);
  }
});*/

var maxAge = 3600000 * 24 * 30;
/*app.use('/upload/', express.static(config.upload_dir, {
  maxAge: maxAge  
}));*/
// old image url: http://host/user_data/images/xxxx
app.use('/data/', express.static(join(__dirname, 'public', 'data'), {
  maxAge: maxAge
}));

var staticDir = join(__dirname, 'public');

app.configure('development', function() {
  app.use(express.static(staticDir));
  app.use(express.errorHandler({
    dumpExceptions: true,
    showStack: true
  }));
});


app.configure('production', function() {
  app.use(express.static(staticDir, {
    maxAge: maxAge
  }));
  app.use(express.errorHandler());
  app.enable('view cache');
});
routes(app,config);
app.use(app.router);
var server = app.listen(config.app.port);

logger.log("Express listening on port " + config.app.port + " in " + app.settings.env + " mode");
logger.log("You can debug your app with http://" + config.app.hostname + ':' + config.app.port);